#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import sys
import os
ProjectPath = os.path.dirname(os.getcwd())
sys.path.insert(0, ProjectPath)
sys.path.insert(0, os.path.join(ProjectPath, 'common'))
sys.path.insert(0, os.path.join(ProjectPath, 'database'))

import wsgiref.handlers
import logging
logging.getLogger().setLevel(logging.DEBUG)

from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template


import databasefunction
import commonfunction
import message.messagedatabase as messagedatabase
import friend.frienddatabase as frienddatabase


PAGE_SIZE = 20

class CMessagePage(commonfunction.CBasePage):
    def get(self):
        TemplateValues = self.GetDefaultTemplateValue()
        TagBox = self.request.get('tagbox', '').encode('UTF-8')
        TemplateValues.update( { 'TagBox':TagBox, } )
        
        TemplateFilePath = self.GetRightLanguageHtmlFilePath('message')

	self.response.out.write(template.render(TemplateFilePath, TemplateValues))

    def head(self):
        pass


class CMessageShowPage(commonfunction.CBasePage):
    def get(self):
        TemplateValues = self.GetDefaultTemplateValue()
        LoginName = commonfunction.GetUserLoginName()
        TimeDelta = self.GetTheSessionTimeDelta()

        CurPage = self.request.get('page', '').encode('UTF-8')
        TemplateValues.update( { 'CurPage':CurPage, } )

        TagBox = self.request.get('tagbox', '').encode('UTF-8')
        TemplateValues.update( { 'TagBox':TagBox, } )

        Messages = None
        PrePage = ''
        NextPage = ''
        if TagBox == 'receive':
            Messages, PrePage, NextPage = databasefunction.GetOneUserTableRecordFromDate('CReceiveMessage', LoginName, PAGE_SIZE, TimeDelta, CurPage, ['LoginName', 'From'])
            TemplateValues.update( { 'Messages':Messages, 'PrePage':PrePage, 'NextPage':NextPage, } )
            TemplateFilePath = self.GetRightLanguageHtmlFilePath('message_list')
        elif TagBox == 'sendout':
            Messages, PrePage, NextPage = databasefunction.GetOneUserTableRecordFromDate('CSendOutMessage', LoginName, PAGE_SIZE, TimeDelta, CurPage)
            
            #修改收件人昵称
            for Item in Messages:
                for i in xrange(len(Item.SendTo)):
                    Item.SendTo[i] = commonfunction.GetOneUserNickName(Item.SendTo[i])
                    if '' == Item.SendTo[i]:
                        Item.SendTo[i] = commonfunction.GetEmptyNickName(TimeDelta)
                        
            TemplateValues.update( { 'Messages':Messages, 'PrePage':PrePage, 'NextPage':NextPage, } )
            TemplateFilePath = self.GetRightLanguageHtmlFilePath('message_list')
        if TagBox == 'delete':
            Messages, PrePage, NextPage = databasefunction.GetOneUserTableRecordFromDate('CDeleteMessage', LoginName, PAGE_SIZE, TimeDelta, CurPage, ['LoginName', 'From'])
            TemplateValues.update( { 'Messages':Messages, 'PrePage':PrePage, 'NextPage':NextPage, } )
            TemplateFilePath = self.GetRightLanguageHtmlFilePath('message_list')
        elif TagBox == 'receiveitem':
            ItemKeyString = self.request.get('item', '').encode('UTF-8')
            CurrentMessage = messagedatabase.ReadOneReceiveMessage(ItemKeyString, TimeDelta)
            TemplateValues.update( { 'CurrentMessage':CurrentMessage, } )
            TemplateFilePath = self.GetRightLanguageHtmlFilePath('message_show')
        elif TagBox == 'sendoutitem':
            ItemKeyString = self.request.get('item', '').encode('UTF-8')
            CurrentMessage = messagedatabase.ReadOneSendOutMessage(ItemKeyString, TimeDelta)
            TemplateValues.update( { 'CurrentMessage':CurrentMessage, } )
            TemplateFilePath = self.GetRightLanguageHtmlFilePath('message_show')
        elif TagBox == 'deleteitem':
            ItemKeyString = self.request.get('item', '').encode('UTF-8')
            CurrentMessage = messagedatabase.ReadOneDeleteMessage(ItemKeyString, TimeDelta)
            TemplateValues.update( { 'CurrentMessage':CurrentMessage, } )
            TemplateFilePath = self.GetRightLanguageHtmlFilePath('message_show')
        elif TagBox == 'write':
            FriendInfos, PrePage, NextPage = frienddatabase.GetOneUserFriendBaseInfoList(LoginName, 1, 100, TimeDelta)
            FriendInfos.sort(lambda x,y:cmp(x.NickName, y.NickName), reverse = False)
            TemplateValues.update( { 'FriendInfos':FriendInfos, 'PrePage':PrePage, 'NextPage':NextPage, } )
            TemplateFilePath = self.GetRightLanguageHtmlFilePath('message_write')

#	self.response.out.write("TemplateValues : %s" % TemplateValues)
	self.response.out.write(template.render(TemplateFilePath, TemplateValues))

    def head(self):
        pass


class CMessageSendPage(commonfunction.CBasePage):
    def post(self):
        TemplateValues = self.GetDefaultTemplateValue()
        LoginName = commonfunction.GetUserLoginName()
        TimeDelta = self.GetTheSessionTimeDelta()

        Title = self.request.get('msgtitle', '')
        Content = self.request.get('msgcontent', '')
        SendToLoginNames = self.request.get('userloginname', allow_multiple=True)
        MsgSendTos = self.request.get('msgsendto', '').strip().split(';')
        #需要将 MsgSendTos 全部转化为 LoginName, 附加到 SendToLoginNames
        for SendTo in MsgSendTos:
            SendTo.strip()
            SendTo.strip(u'　')   #全角空格
            if 0 < len(SendTo):
                AddLoginName = commonfunction.GetOneUserLoginName(SendTo)
                SendToLoginNames.append(AddLoginName)

        FailUsers = messagedatabase.SendOneMessage(SendToLoginNames, Title, Content)
        if 1 > len(FailUsers):
            if self.GetTheSessionLanguage() == 'zh-cn':
                TemplateValues.update( { 'Error':u'发送成功', } )
            else:
                TemplateValues.update( { 'Error':u'Send Finish.', } )
        else:
            FailString = ";".join(FailUsers)
            if self.GetTheSessionLanguage() == 'zh-cn':
                TemplateValues.update( { 'Error':u'下列用户发送失败：' + FailString, } )
            else:
                TemplateValues.update( { 'Error':u'Send Fail users:' + FailString, } )


        TemplateValues.update( { 'BackUrl':'/message_show?tagbox=sendout', } )
        TemplateFilePath = self.GetRightLanguageHtmlFilePath('error')
        self.response.out.write(template.render(TemplateFilePath, TemplateValues))
        


class CMessageSendRpcPage(commonfunction.CBasePage):
    def post(self):
#        TemplateValues = self.GetDefaultTemplateValue()
#        LoginName = commonfunction.GetUserLoginName()
#        TimeDelta = self.GetTheSessionTimeDelta()
        
        ParamsDictionary = simplejson.loads(self.request.body)
#        logging.error("----------CMessageSendRpcPage 1 self.request.body = %s, ParamsDictionary = %s" % (self.request.body, ParamsDictionary))

        SendToLoginName = ParamsDictionary['msgtologinname'].encode('UTF-8')
#        Title = ParamsDictionary['msgtitle'].encode('UTF-8')
#        Content = ParamsDictionary['msgcontent'].encode('UTF-8')
        Title = ParamsDictionary['msgtitle']
        Content = ParamsDictionary['msgcontent']

        SendToList = SendToLoginName.split(';')
        FailUsers = messagedatabase.SendOneMessage(SendToList, Title, Content)
        if 1 > len(FailUsers):
            self.response.out.write(simplejson.dumps(1))
        else:
            self.response.out.write(simplejson.dumps(0))
            



class CMessageDeletePage(commonfunction.CBasePage):
    def post(self):
        TemplateValues = self.GetDefaultTemplateValue()
        TimeDelta = self.GetTheSessionTimeDelta()
        
        TagBox = self.request.get('tagbox', '').encode('UTF-8')
        TemplateValues.update( { 'TagBox':TagBox, } )
        LoginName = commonfunction.GetUserLoginName()
        if 1 > len(LoginName):
            self.redirect('/')
            return

        if 'receiveitem' == TagBox:
            ItemKeyString = self.request.get('item', '').encode('UTF-8')
            DeleteItem = databasefunction.GetOneTableItem('CReceiveMessage', ItemKeyString)
            if DeleteItem is None:
                self.redirect('/message_show?tagbox=receive')
                return
            
            Messages, PrePage, NextPage = databasefunction.GetOneUserTableRecordFromDate('CReceiveMessage', LoginName, 2, TimeDelta, str(DeleteItem.Date))
            
            messagedatabase.DeleteOneReceiveMessage(ItemKeyString)
            
            if Messages is None:
                self.redirect('/message_show?tagbox=receive')
                return

            if 2 > len(Messages):
                self.redirect('/message_show?tagbox=receive')
                return
            else:
                CurrentMessage = Messages[1]
                self.redirect('/message_show?tagbox=receiveitem&item=' + CurrentMessage.key())
                return
        elif 'sendoutitem' == TagBox:
            ItemKeyString = self.request.get('item', '').encode('UTF-8')
            DeleteItem = databasefunction.GetOneTableItem('CSendOutMessage', ItemKeyString)
            if DeleteItem is None:
                self.redirect('/message_show?tagbox=sendout&err=NoItem')
                return
            
            Messages, PrePage, NextPage = databasefunction.GetOneUserTableRecordFromDate('CSendOutMessage', LoginName, 2, TimeDelta, str(DeleteItem.Date))
            
            messagedatabase.DeleteOneSendOutMessage(ItemKeyString)
            
            if Messages is None:
                self.redirect('/message_show?tagbox=sendout&err=NoMessages')
                return

            if 2 > len(Messages):
                self.redirect('/message_show?tagbox=sendout&err=NoNewCur')
                return
            else:
                CurrentMessage = Messages[1]
                self.redirect('/message_show?tagbox=sendoutitem&item=' + CurrentMessage.key())
                return
        elif 'deleteitem' == TagBox:
            ItemKeyString = self.request.get('item', '').encode('UTF-8')
            DeleteItem = databasefunction.GetOneTableItem('CDeleteMessage', ItemKeyString)
            if DeleteItem is None:
                self.redirect('/message_show?tagbox=delete')
                return
            
            Messages, PrePage, NextPage = databasefunction.GetOneUserTableRecordFromDate('CDeleteMessage', LoginName, 2, TimeDelta, str(DeleteItem.Date))
            
            messagedatabase.DeleteOneDeleteMessage(ItemKeyString)
            
            if Messages is None:
                self.redirect('/message_show?tagbox=delete')
                return

            if 2 > len(Messages):
                self.redirect('/message_show?tagbox=delete')
                return
            else:
                CurrentMessage = Messages[1]
                self.redirect('/message_show?tagbox=deleteitem&item=' + CurrentMessage.key())
                return
        elif 'receive' == TagBox:
            DeleteItems = self.request.get('selectitem', allow_multiple=True)
            for OneItem in DeleteItems:
                messagedatabase.DeleteOneReceiveMessage(OneItem)

            self.redirect('/message_show?tagbox=receive')
            return
        elif 'sendout' == TagBox:
            DeleteItems = self.request.get('selectitem', allow_multiple=True)
            for OneItem in DeleteItems:
                messagedatabase.DeleteOneSendOutMessage(OneItem)

            self.redirect('/message_show?tagbox=sendout')
            return
        elif 'delete' == TagBox:
            DeleteItems = self.request.get('selectitem', allow_multiple=True)
            for OneItem in DeleteItems:
                messagedatabase.DeleteOneDeleteMessage(OneItem)

            self.redirect('/message_show?tagbox=delete')
            return










def main():
    application = webapp.WSGIApplication([
                                            ('/message', CMessagePage),
                                            ('/message_show', CMessageShowPage),
                                            ('/message_send', CMessageSendPage),
                                            ('/message_send_rpc', CMessageSendRpcPage),
                                            ('/message_delete', CMessageDeletePage),
                                         ], debug=True)
    
    wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
    main()


